# -*- coding: UTF-8 -*-
# @Time : 2021/12/23 0023 14:42
# @Author : lyw
# @Remark : 空调baseServer
import datetime
import re
import time
from typing import List

from mxsoftpy import Server

try:
    from opm_pyirm import GetStatusById
except ImportError:
    try:
        from bsmiddle import GetStatusById
    except ImportError:
        def GetStatusById(*args):
            return 1, 2
from utils.classes.custom_exception import VerifyError
from utils.public.params_method import paging_data, get_pagination_params


class IOTBaseServer(Server):
    s_run = "run"
    s_state = "state"
    run_state = "run_state"
    m_run = "ac_mode"
    m_filed_run = "ups_run"
    search = "name"

    def search_data(self, device_list, kwargs):
        """
        搜索数据
        """
        # 状态定义
        state = {"2": (0, 5), "0": (1,), "1": (2, 3, 4), 2: (0, 5), 0: (1,), 1: (2, 3, 4)}
        # 运行模式 定义
        run_mode = {"0": "关", "1": "开"}
        # 运行模式 过滤
        if run_mode.get(kwargs.get(self.s_run)):
            run_list = []
            for search_data in device_list:
                if search_data[self.run_state] == run_mode[kwargs.get(self.s_run)]:
                    run_list.append(search_data)
            device_list = run_list

        if kwargs.get(self.m_filed_run):
            run_list = []
            pattern = '.*?'.join(kwargs[self.m_filed_run])
            regex = re.compile(pattern)  # Compiles a regex.
            for search_data in device_list:
                if regex.search(search_data[self.m_run]):
                    run_list.append(search_data)
            device_list = run_list

        if state.get(kwargs.get(self.s_state)):
            state_list = []
            for dev_data in device_list:
                status = GetStatusById(dev_data["code"])[1]
                if status in state[kwargs.get(self.s_state)]:
                    state_list.append(dev_data)
            device_list = state_list
        return device_list

    @staticmethod
    def statistics_count(device_list: List[dict]):
        """
        数量统计
        @param device_list:
        @return:
        """
        count_int = {"total": 0, "normal": 0, "alarm": 0, "offline": 0}
        for device in device_list:
            status = GetStatusById(device["code"])
            if isinstance(status, int):
                ac_status = status
            else:
                ac_status = status[1]
            if ac_status in (2, 3, 4):
                count_int["alarm"] += 1
            elif ac_status in (0, 5):
                count_int["offline"] += 1
            else:
                count_int["normal"] += 1
            # 统计数量
            count_int["total"] += 1
        return count_int

    def process_time(self, **kwargs):
        """
        时间处理
        @param kwargs:
        @return:
        """
        if kwargs.get("alert_time") in ("0", "1", "3", "7", "30"):
            end_time = datetime.datetime.now()
            if kwargs["alert_time"] == "0":
                start_time = datetime.datetime.fromtimestamp(time.mktime(datetime.date.today().timetuple()))
            else:
                start_time = end_time - datetime.timedelta(days=int(kwargs["alert_time"]))

        else:
            if kwargs.get("start_time") and kwargs.get("end_time"):
                start_time = datetime.datetime.strptime(kwargs["start_time"].replace("+", " "), "%Y-%m-%d %H:%M:%S")
                end_time = datetime.datetime.strptime(kwargs["end_time"].replace("+", " "), "%Y-%m-%d %H:%M:%S")
            else:
                raise VerifyError("alert_time 参数 或者 start_time 和end_time 参数错误")
        if start_time > end_time:
            raise VerifyError("开始时间大于结束时间")

        return start_time, end_time

    def alert_info(self, device_data, info_data):
        # 获取告警数据
        for alert_dev_key, alert_info in self.db.get_alert_data().items():
            if re.search(device_data["code"].replace(".", "\."), alert_dev_key):
                info_data["alarm_info"] = alert_info
                break

    def device_info(self, device_list):
        pass

    def select(self, device=None, **kwargs):
        if device is None:
            device_list = self.db.query_device(name=kwargs.get(self.search, ""), code=kwargs.get("code", None))
        else:
            device_list = device
        # 获取设备参数 并且进行搜索
        res_device_data = self.search_data(self.device_info(device_list), kwargs)

        # 分页功能
        paging_data_dict = paging_data(res_device_data, **get_pagination_params(kwargs))

        res_dict = {"count": self.statistics_count(self.db.query_device(name="")),
                    "data": paging_data_dict.pop("data")}
        res_dict.update(paging_data_dict)
        return res_dict

    def set_state(self, status):
        """
        获取状态类型
        @param status:
        @return:
        """
        if status in (2, 3, 4):
            return 1
        if status in (0, 5):
            return 2
        else:
            return 0
